<script lang="ts" setup>
import { reactive, provide } from "vue";
import Top from "../components/Top.vue";
import ProductCard from "../components/ProductCard.vue";
import ShoppingCart from "../components/ShoppingCart.vue";
import Foot from "../components/Foot.vue";
const cart = reactive<{
  items: Product[];
  addItem: (product: Product) => void;
  removeItem: (productId: number) => void;
  total: number;
}>({
  items: [],
  addItem: (product) => {
    const existingItem = cart.items.find((item) => item.id === product.id);
    if (existingItem) {
      existingItem.quantity = (existingItem.quantity || 1) + 1;
    } else {
      cart.items.push({ ...product, quantity: 1 });
    }
    updateTotal();
  },
  removeItem: (productId) => {
    const index = cart.items.findIndex((item) => item.id === productId);
    if (index !== -1) {
      cart.items.splice(index, 1);
      updateTotal();
    }
  },
  total: 0,
});
// 更新总价
const updateTotal = () => {
  cart.total = cart.items.reduce(
    (sum, item) => sum + item.price * (item.quantity || 1),
    0
  );
};
// 使用 provide
provide("cart", cart);
export interface Product {
  id: number;
  name: string;
  describe: string;
  price: number;
  isHot?: boolean;
  quantity?: number; // 只在购物车中使用
}
const products = reactive<Product[]>([
  {
    id: 3,
    name: "懒人小沙发",
    describe: "舒适休闲，完善支撑",
    price: 126.4,
    isHot: 1,
  },
  { id: 4, name: "减压弹力球", describe: "释放压力，放松身心", price: 95.2 },
  { id: 5, name: "简约一字发夹", describe: "简约设计，百搭款式", price: 15.9 },
  {
    id: 6,
    name: "毛线小兔子耳朵发夹",
    describe: "可爱萌趣，精致做工",
    price: 12.7,
  },
  {
    id: 7,
    name: "华为畅享 60X",
    describe: "7000mA 大电池鸿蒙系统",
    price: 688,
    isHot: 1,
  },
]);
function furemoveItem() {
  console.log("furemoveItem");
}
</script>
<template>
  <Top />
  <div class="container">
    <h1>商品</h1>
    <div class="list_ul">
      <ProductCard
        v-for="product in products"
        :key="product.id"
        :product="product"
      />
    </div>
    <ShoppingCart></ShoppingCart>
  </div>
  <Foot />
</template>
<style scoped>
.container {
  width: 1200px;
  margin: 0 auto;
}
.list_ul {
  width: 1280px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
}
</style>
